package com.example.yz.happywoker;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.LogUtil;
import com.avos.avoscloud.SaveCallback;
import com.example.yz.happywoker.Dialog.CustomDialog;
import com.example.yz.happywoker.Dialog.SelfDialog;
import com.example.yz.happywoker.lib.ActivityList;
import com.example.yz.happywoker.lib.Constants;
import com.example.yz.happywoker.service.PollingService;
import com.example.yz.happywoker.service.PollingUtils;
import com.example.yz.happywoker.service.ServiceOne;
import com.example.yz.happywoker.service.ServiceTwo;
import com.example.yz.happywoker.timeline.MyWalletActivity;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.amap.api.mapcore.util.az.e;
import static com.example.yz.happywoker.DetailedInforMapActivity.ConverToString;


public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener, AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter, AMap.OnMarkerClickListener, View.OnClickListener {

    private static String TAG = "MainActivity";
    private Toolbar mToolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private NavigationView mNavigationView;
    private MapView mapView;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private SelfDialog selfDialog;
    private Marker locationMarker;
    private LatLonPoint searchLatlonPoint;
    private Bundle bundle;
    private LinearLayout fresh;
    private List<PoiItem> resultData;
    private boolean isFirst = true;
    private double lat;
    private double lon;
    //定时器：定时从后台读取数据
    private int i = 0;
    private CustomDialog.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//不在活动中显示标题栏
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        ActivityList.getInstance().addActivity(this);
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        bundle = new Bundle();
        init();
        findViews();
        setupToolbar();
        setupDrawerContent(mNavigationView);
        mToggle = setupDrawerToggle();
        InitService();
    }


    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_websearch:
                Intent intent = new Intent();
                intent.putExtra("lat", lat);
                intent.putExtra("log", lon);
                intent.setClass(this, ListViewActivity.class);
                startActivity(intent);
                Toast.makeText(this, "列表查看", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }


    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.getUiSettings().setRotateGesturesEnabled(false);
            resultData = new ArrayList<>();
            if (isNetworkAvailable(this)) {
                setUpMap();
            } else {
                Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void clearMarkers() {
        List<Marker> mapScreenMarkers = aMap.getMapScreenMarkers();
        for (int i = 0; i < mapScreenMarkers.size(); i++) {
            if (!mapScreenMarkers.get(i).equals(locationMarker)) {
                Marker markerer = mapScreenMarkers.get(i);
                markerer.remove();//移除当前Marker
            }
        }
    }

    private void setMyPointMarker() {
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (isNetworkAvailable(MainActivity.this)) {
                    clearMarkers();
                    searchLatlonPoint = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
                    if (searchLatlonPoint != null) {
                        resultData.clear();
                        AVQuery<AVObject> query = new AVQuery<>("MyOrderList");
                        AVGeoPoint point = new AVGeoPoint(searchLatlonPoint.getLatitude(), searchLatlonPoint.getLongitude());
                        query.limit(10);
                        query.whereNear("Location", point);
                        query.findInBackground(new FindCallback<AVObject>() {
                            @Override
                            public void done(List<AVObject> list, AVException e) {
                                if(list!=null) {

                                    //  List<AVObject> nearbyTodos = list;// 离这个位置最近的 10 个 Todo 对象
                                    for (AVObject avObject : list) {
                                        GlobalData.nearby.add(avObject);
                                        getMarket();
                                    }
                                }
                            }
                        });
                    }
                    Log.i("MY", "geoAddress" + searchLatlonPoint.getLatitude() + "   " + searchLatlonPoint.getLongitude());
                } else {
                    Toast.makeText(MainActivity.this, "当前无网络连接", Toast.LENGTH_LONG).show();
                }
            }
        });
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkerInScreenCenter();//加入自定义的标记点
            }
        });
    }

    private void addMarkerInScreenCenter() {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        locationMarker = aMap.addMarker(new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.purple_pin)));
        locationMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        locationMarker.setZIndex(1);
    }

    private void getMarket() {
        int i = GlobalData.nearby.size() - 1;
        if (GlobalData.nearby.get(i).get("Status").equals("1")) {
            MarkerOptions markerOption = new MarkerOptions();
            try {
                LatLng ll_cun = new LatLng(GlobalData.nearby.get(i).getJSONObject("Location").getDouble("latitude"), GlobalData.nearby.get(i).getJSONObject("Location").getDouble("longitude"));
                aMap.addMarker(markerOption.position(ll_cun).title(GlobalData.nearby.get(i).get("RepairCategory").toString())
                        .snippet(GlobalData.nearby.get(i).getObjectId())//获取标记点的ID?
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.work)));
            } catch (JSONException exception) {
            }
        }
    }

    private void setUpMap() {
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置
        // 设置定位资源
        aMap.setLocationSource(this);
        aMap.setMyLocationEnabled(true);// 设置为true表示系统定位按钮显示并响应点击，false表示隐藏，默认是false
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
        sHA1(this);
        setMyPointMarker();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                if (isFirst) {  //初始化第一次定位，完成之后不会在自动定位
                    isFirst = false;
                    lat = amapLocation.getLatitude();
                    lon = amapLocation.getLongitude();
                    Log.v("pcw", "lat : " + lat + " lon : " + lon);
                    Log.v("pcw", "Country : " + amapLocation.getCountry() + " province : " + amapLocation.getProvince() + " City : " + amapLocation.getCity() + " District : " + amapLocation.getDistrict());
                    // 设置当前地图显示为当前位置
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 13));//设置缩放级别
                }


            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            mlocationClient.setLocationListener(this);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(200000);
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    private void findViews() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
    }

    private void setupToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }

    private ActionBarDrawerToggle setupDrawerToggle() {
        return new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
                R.string.drawer_open, R.string.drawer_close);
    }

    public void selectDrawerItem(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.nav_first_fragment:
                Intent intent = new Intent(MainActivity.this, MyOrder.class);
                startActivity(intent);
                break;
//            case R.id.nav_second_fragment:
//                Intent intent02 = new Intent();
//                intent02.setClass(this, HistoryOrder.class);
//                startActivity(intent02);
//                break;

            case R.id.nav_third_fragment:
                Intent intent03 = new Intent();
                intent03.setClass(MainActivity.this, SuggestionActivity.class);
                startActivity(intent03);
                break;
            case R.id.nav_fourth_fragment:
                Intent intent04 = new Intent();
                intent04.setClass(MainActivity.this, MyWalletActivity.class);
                startActivity(intent04);
                break;
            case R.id.nav_fifth_fragment:
                Intent intent05 = new Intent();
                intent05.setClass(MainActivity.this, SettingActivity.class);
                startActivity(intent05);
                break;
            default:
        }
        menuItem.setChecked(true);
    }

    @Override
    public void onBackPressed() {
        if (isNavDrawerOpen()) {
            closeNavDrawer();
        } else {
            super.onBackPressed();
        }
    }

    protected boolean isNavDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
    }

    protected void closeNavDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }


    public void getAdmition() {
        AVUser currentUser = AVUser.getCurrentUser();
        AVObject todo = AVObject.createWithoutData("MyOrderList", GlobalData.MyObjectIdG);
        Log.e("fhjfhfgf", "" + GlobalData.MyObjectIdG);
        todo.put("Status", "2");
        todo.put("WokerID", currentUser.getUsername());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        todo.put("HandleTime", ConverToString(curDate));
        todo.saveInBackground();     // 保存到云端
        Toast.makeText(getApplication(), "接单成功", Toast.LENGTH_SHORT).show();
        AVUser.getCurrentUser().put("Busy", "1");
        AVUser.getCurrentUser().saveInBackground(); // 保存到云端
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {

        if (isNetworkAvailable(this)) {

            if (marker.equals(locationMarker)) {
                return false;
            } else {
                marker.hideInfoWindow();
                selfDialog = new SelfDialog(this);
                selfDialog.setMessage(marker.getTitle());
                selfDialog.setDetailOnclickListener("查看详情", new SelfDialog.onDetailOnclickListener() {
                    @Override
                    public void onNoClick() {
                        Toast.makeText(MainActivity.this, "点击了查看详情", Toast.LENGTH_SHORT).show();
                        selfDialog.dismiss();
                        Intent intent = new Intent();
                        intent.putExtra("id", marker.getSnippet());
                        intent.setClass(MainActivity.this, DetailedInforMapActivity.class);
                        startActivity(intent);
                    }
                });
                selfDialog.show();
            }
        } else {
            Toast.makeText(MainActivity.this, "当前无网络连接", Toast.LENGTH_LONG).show();
        }
        return true;//注意：false时候marker.hideInfoWindow()不起作用
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case fresh_lin:
//                aMap.clear();
//                aMap.setMyLocationEnabled(false);
//                deactivate();
//                setUpMap();
//                Log.e("this",""+"ccccc");

            //          break;
        }
    }


    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            Log.i("result", result);
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static boolean isServiceWorked(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    private void InitService() {
        Intent serviceOne = new Intent();
        serviceOne.setClass(MainActivity.this, ServiceOne.class);
        startService(serviceOne);
        PollingUtils.startPollingService(this, Constants.POLLINGTime, PollingService.class, PollingService.ACTION);
        Intent serviceTwo = new Intent();
        serviceTwo.setClass(MainActivity.this, ServiceTwo.class);
        startService(serviceTwo);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String status) {
        Log.e(TAG, "onMessageEvent");
        handleSomethingElse(status);
        Log.e("statusYZ",status);
    };

    @Subscribe
    public void handleSomethingElse(String status) {
        Log.e(TAG, "handleSomethingElse");
        if(Constants.isDialogShow ) {
            Constants.isDialogShow = true;
            if (status.equals("2")) {
                builder = new CustomDialog.Builder(MainActivity.this);
                builder.setMessage("抢单成功 请及时与雇主进行联系");
                builder.setTitle("提示");
                builder.setNegativeButton("知道了",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();
                                intent.setClass(MainActivity.this, MyOrder.class);
                                startActivity(intent);
                                GlobalData.IdG = null;
                                dialog.dismiss();
                            }
                        });

                builder.create().show();
                AVObject todoer = AVObject.createWithoutData("RobMyOrderList", GlobalData.IdG);
                todoer.put("State", "3");
                todoer.saveInBackground();
                GlobalData.IdG = null;
                getAdmition();//雇主同意方为接单成功
            } else if (status.equals("4")) {
                CustomDialog.Builder builder = new CustomDialog.Builder(MainActivity.this);
                builder.setMessage("雇主拒绝您的请求");
                builder.setTitle("提示");
                builder.setNegativeButton("知道了",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                AVObject todoer = AVObject.createWithoutData("RobMyOrderList", GlobalData.IdG);
                                todoer.put("State", "5"); //工人知道了雇主的不同意请求
                                todoer.saveInBackground();
                                dialog.dismiss();
                                GlobalData.IdG = null;
                            }
                        });
                builder.create().show();
            }
        }
    }

}
